package com.yisu.expressway.onedollar.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.model.UserAddressItem;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.ui.MultiButtonDialog;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.ui.refresh.SuperSwipeRefreshLayout;
import com.yisu.expressway.utils.ToastUtil;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Kaven on 2016/12/20.
 */

public class UserAddressActivity extends BasicActivity
        implements PagingRecyclerView.SampleActionListener {
    public static final int REQUEST_CODE_NORMAL = 1;
    public static final int REQUEST_CODE_SELECT = 2;
    public static final String EXTRA_KEY_RESULT = "extra_key_result";
    public static final String EXTRA_KEY_RESULT_ORDER_ID = "extra_key_result_order_id";
    private static final String EXTRA_KEY_REQUEST = "extra_key_request";
    private static final String EXTRA_KEY_ORDER_ID = "extra_key_order_id";
    @Bind(R.id.title_bar)
    protected TitleView mTitleView;
    @Bind(R.id.refreshLayout)
    protected SuperSwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.rv_content)
    protected PagingRecyclerView mRecyclerView;
    @Bind(R.id.tv_new)
    protected TextView mNewTv;
    @Bind(R.id.empty)
    protected View mEmptyView;
    @Bind(R.id.empty_des)
    protected TextView mEmptyDesTv;
    @Bind(R.id.empty_action)
    protected TextView mEmptyActionTv;
    @Bind(R.id.empty_iv)
    protected ImageView mEmptyIv;
    private ImageView carImage;
    private AnimationDrawable mAnimation;
    private boolean isFreshEnable;
    private List<UserAddressItem> mUserAddressItems = new ArrayList<>();
    private long mOrderId;
    private int mRequestCode = -1;
    private UserAddressItem mSelectedAddress;

    public static void launch(Activity context, int requestCode, long orderId) {
        Intent intent = new Intent(context, UserAddressActivity.class);
        intent.putExtra(EXTRA_KEY_REQUEST, requestCode);
        intent.putExtra(EXTRA_KEY_ORDER_ID, orderId);
        context.startActivityForResult(intent, requestCode);
    }

    @OnClick(R.id.tv_new)
    void onNewClick() {
        if (mRequestCode == REQUEST_CODE_SELECT) {
            if (mSelectedAddress == null) {
                ToastUtil.showMessage(this, "请选择一个地址");
                return;
            }
            Intent intent = new Intent();
            intent.putExtra(EXTRA_KEY_RESULT, mSelectedAddress);
            if (mOrderId > 0) {
                intent.putExtra(EXTRA_KEY_RESULT_ORDER_ID, mOrderId);
            }
            setResult(RESULT_OK, intent);
            finish();
        } else {
            if (mUserAddressItems == null || mUserAddressItems.isEmpty()) {
                UserAddressBuildActivity.launch(this, UserAddressBuildActivity.BUILD_TYPE_INSERT,
                        null, true, -1);
            } else {
                UserAddressBuildActivity.launch(this, UserAddressBuildActivity.BUILD_TYPE_INSERT,
                        null, false, -1);
            }
        }

    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarTheme;
    }

    @Override
    protected int getInflateLayoutId() {
        return R.layout.onedollar_user_address;
    }

    @Override
    protected void initPresenter() {

    }

    @Override
    protected void releasePresenter() {

    }

    @Override
    protected void getIntentData(Intent intent) {
        int intExtra = intent.getIntExtra(EXTRA_KEY_REQUEST, -1);
        mRequestCode = intExtra;
        switch (mRequestCode) {
            case REQUEST_CODE_NORMAL:
                break;
            case REQUEST_CODE_SELECT:
                long longExtra = intent.getLongExtra(EXTRA_KEY_ORDER_ID, -1);
                if (longExtra < 0) {
                    finish();
                    return;
                }
                mOrderId = longExtra;
                break;
            default:
                finish();
                break;
        }
    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews() {
        initFreshLayout();
        DividerListItemDecoration mListDivider = new DividerListItemDecoration(this,
                LinearLayoutManager.VERTICAL);
        mRecyclerView.init(mListDivider, new LinearLayoutManager(this), this, 20);
        if (mRequestCode == REQUEST_CODE_SELECT) {
            mNewTv.setText(R.string.submit);
        } else {
            mNewTv.setText(R.string.one_dollar_user_address_new);
        }
        mEmptyIv.setVisibility(View.GONE);
        mEmptyActionTv.setVisibility(View.GONE);
    }

    private View createHeaderView() {
        View headerView = getLayoutInflater().inflate(R.layout.layout_head, null);
        carImage = (ImageView) headerView.findViewById(R.id.pb_view);
        return headerView;
    }

    private void initFreshLayout() {
        mRefreshLayout.setHeaderViewBackgroundColor(0xffefeff4);
        mRefreshLayout.setHeaderView(createHeaderView());
        mRefreshLayout.setTargetScrollWithLayout(true);
        mRefreshLayout
                .setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

                    @Override
                    public void onRefresh() {
                        if (mAnimation != null) {
                            mAnimation.start();
                        }

                        mRecyclerView.refreshData();
                    }

                    @Override
                    public void onPullDistance(int distance) {
                        int index = distance / 25;

                        int resId = R.drawable.car_1;
                        switch (index) {
                            case 2:
                                resId = R.drawable.car_2;
                                break;
                            case 3:
                                resId = R.drawable.car_3;
                                break;
                            case 4:
                                resId = R.drawable.car_4;
                                break;
                            case 5:
                                resId = R.drawable.car_5;
                                break;
                            case 6:
                                resId = R.drawable.car_6;
                                break;
                            case 7:
                                resId = R.drawable.car_7;
                                break;
                            case 8:
                                resId = R.drawable.car_8;
                                break;
                            case 9:
                                resId = R.drawable.car_9;
                                break;
                            case 10:
                                resId = R.drawable.car_10;
                                break;
                        }
                        if (!isFreshEnable) {
                            carImage.setBackgroundResource(resId);
                        }

                    }

                    @Override
                    public void onPullEnable(boolean enable) {
                        isFreshEnable = enable;
                        if (enable) {
                            carImage.setBackgroundResource(R.color.colorTransparent);
                            carImage.setImageResource(R.drawable.car_frame);
                            mAnimation = (AnimationDrawable) carImage.getDrawable();
                        }
                    }
                });

    }

    @Override
    protected void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                finishSelf();
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {

            }
        });
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    @Override
    public void fetchData(int start, int pageSize) {

        getAddressList();
    }

    private void getAddressList() {
        ApiClientHelper.postApi(ApiSetting.getUserAddressList(),
                new TypeToken<List<UserAddressItem>>() {
                }, "", new Response.Listener<ApiResult<List<UserAddressItem>>>() {
                    @Override
                    public void onResponse(ApiResult<List<UserAddressItem>> result) {
                        if (!result.success) {
                            mEmptyView.setVisibility(View.VISIBLE);
                            mEmptyDesTv.setText(getString(R.string.one_dollar_empty_net_error));
                            mRecyclerView.dataFetchFail(result.getMsg());
                            return;
                        }
                        List<UserAddressItem> result1 = result.getResult();
                        if (result1 != null && !result1.isEmpty()) {
                            mEmptyView.setVisibility(View.GONE);
                            mRefreshLayout.setVisibility(View.VISIBLE);
                            mUserAddressItems = result.getResult();
                        } else {
                            mRefreshLayout.setVisibility(View.GONE);
                            mEmptyView.setVisibility(View.VISIBLE);
                            mEmptyDesTv.setText(getString(R.string.one_dollar_empty_ordershow));
                        }

                        mRecyclerView.dataFetchDone(mUserAddressItems);
                        if (mAnimation != null) {
                            mRefreshLayout.setRefreshing(false);
                            mAnimation.stop();
                            carImage.setImageResource(R.color.colorTransparent);
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        mRecyclerView.dataFetchFail(volleyError.getMessage());
                        mRefreshLayout.setVisibility(View.GONE);
                        mEmptyView.setVisibility(View.VISIBLE);
                        mEmptyDesTv.setText(getString(R.string.one_dollar_empty_net_error));
                    }
                }, this);
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(this).inflate(R.layout.user_address_item_list, null);
        return new UserAddressViewHolder(itemView);
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, final int position, Object _item) {
        final UserAddressViewHolder holder = (UserAddressViewHolder) _holder;
        final UserAddressItem item = (UserAddressItem) _item;
        holder.mConsigneeNameTv.setText(item.consigneeName);
        holder.mConsigneePhoneTv.setText(item.consigneePhone);
        holder.mAddressTv.setText(item.toString());
        holder.mSelCb.setVisibility(mOrderId > 0 ? View.VISIBLE : View.GONE);
        holder.mSelCb.setChecked(item.isSelected());
        holder.mDefaultCb.setEnabled(item.isDefault == 0);
        holder.mDefaultCb.setChecked(item.isDefault == 1);
        holder.mDefaultCb.setTag(item.recordId);
        holder.mDefaultCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (item.recordId == (long) buttonView.getTag()) {
                    item.isDefault = isChecked ? 1 : 0;
                    updateUserAddress(item);

                }
            }
        });

        holder.mEditTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserAddressBuildActivity.launch(UserAddressActivity.this,
                        UserAddressBuildActivity.BUILD_TYPE_UPDATE, item, false, -1);
            }
        });
        holder.mDelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteAddress(item.recordId);

            }
        });
        holder.mSelCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                for (UserAddressItem mUserAddressItem : mUserAddressItems) {
                    mUserAddressItem.setSelected(false);
                }
                mUserAddressItems.get(position).setSelected(true);
                mRecyclerView.dataFetchDone(mUserAddressItems);
                mSelectedAddress = mUserAddressItems.get(position);
            }
        });
    }

    private void deleteAddress(long recordId) {
        if (recordId < 0) {
            return;
        }
        Map<String, Object> params = new HashMap();

        params.put("recordId", recordId);
        ApiClientHelper.postApi(ApiSetting.deleteUserAddress(), new TypeToken<Object>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
            @Override
            public void onResponse(ApiResult<Object> result) {
                if (!result.success) {
                    ToastUtil.showMessage(UserAddressActivity.this,
                            getString(R.string.one_dollar_user_address_del_failed));
                }
                ToastUtil.showMessage(UserAddressActivity.this,
                        getString(R.string.one_dollar_user_address_del_suc));
                mRecyclerView.refreshData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.showMessage(UserAddressActivity.this,
                        getString(R.string.one_dollar_user_address_del_failed));
                mRecyclerView.refreshData();
            }
        }, this);
    }

    private void finishSelf() {
        if (mRequestCode == REQUEST_CODE_SELECT) {
            if (mUserAddressItems == null || mUserAddressItems.isEmpty()) {
                showQuitWarningDlg();
            } else {
                finish();
            }
        } else {
            finish();
        }

    }

    private void showQuitWarningDlg() {
        final MultiButtonDialog multiButtonDialog = new MultiButtonDialog(UserAddressActivity.this);
        multiButtonDialog.show();
        multiButtonDialog.setButtonColor(R.color.oneDollarCommon);
        multiButtonDialog.setContentText(R.string.one_dollar_user_address_select_quit_warnning);
        multiButtonDialog.setPositiveClickListener(new MultiButtonDialog.PositiveClickListener() {
            @Override
            public void onPositiveClick(String inputContent) {
                multiButtonDialog.dismiss();

            }
        });
        multiButtonDialog.setNegativeClickListener(new MultiButtonDialog.NegativeClickListener() {
            @Override
            public void onNegativeClick(String inputContent) {
                multiButtonDialog.dismiss();
                finish();
            }
        });
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finishSelf();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private void updateUserAddress(final UserAddressItem item) {
        if (item == null) {
            return;
        }
        Map<String, Object> params = new HashMap();

        params.put("address", item.address);
        params.put("area", item.area);
        params.put("city", item.city);
        params.put("consigneeName", item.consigneeName);
        params.put("consigneePhone", item.consigneePhone);
        params.put("isDefault", item.isDefault);
        params.put("province", item.province);
        params.put("recordId", item.recordId);
        ApiClientHelper.postApi(ApiSetting.updateUserAddress(), new TypeToken<Object>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
            @Override
            public void onResponse(ApiResult<Object> result) {
                if (!result.success) {
                    ToastUtil.showMessage(UserAddressActivity.this,
                            getString(R.string.one_dollar_user_address_modify_failed));
                }
                ToastUtil.showMessage(UserAddressActivity.this,
                        getString(R.string.one_dollar_user_address_modify_suc));
                mRecyclerView.refreshData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtil.showMessage(UserAddressActivity.this,
                        getString(R.string.one_dollar_user_address_modify_failed));
                mRecyclerView.refreshData();
            }
        }, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case UserAddressBuildActivity.BUILD_TYPE_INSERT:
                case UserAddressBuildActivity.BUILD_TYPE_UPDATE:
                    mRecyclerView.refreshData();
                    break;
                default:
                    break;
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    class UserAddressViewHolder extends BaseRvAdapter.SampleViewHolder {
        @Bind(R.id.rootView)
        View mRootView;
        @Bind(R.id.tv_name)
        TextView mConsigneeNameTv;
        @Bind(R.id.tv_phone_num)
        TextView mConsigneePhoneTv;
        @Bind(R.id.tv_address)
        TextView mAddressTv;
        @Bind(R.id.cb_default)
        CheckBox mDefaultCb;
        @Bind(R.id.tv_edit)
        TextView mEditTv;
        @Bind(R.id.tv_delete)
        TextView mDelTv;
        @Bind(R.id.cb_select)
        CheckBox mSelCb;

        public UserAddressViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
